//
// Created by hunan on 25-7-27.
//

#include "loop_pool.h"
#include "loop.h"
#include <unistd.h>
#include "./../timer/timer_task.h"

LoopPool::LoopPool()
{
    m_loop_pool.clear();
}

LoopPool::~LoopPool()
{
    m_loop_pool.clear();
}

bool LoopPool::Initialize(int num, IoReuseModuleFactory* factory)
{
    if (!m_loop_pool.empty())
    {
        return false;
    }
    for (int i = 0; i < num; i++)
    {
        auto pool_data = std::make_shared<LoopData>();
        pool_data->m_status = true;
        pool_data->m_loop   = std::make_shared<Loop>(factory);
        pool_data->m_schedule_event = std::make_shared<TimerTask>(pool_data->m_loop.get());
        pool_data->m_thread = std::thread(&LoopPool::StartThread, this, pool_data);
        m_loop_pool.push_back(pool_data);
    }
    return true;
}

Loop * LoopPool::GetLoop(int index) const
{
    index = index % m_loop_pool.size();
    return m_loop_pool[index]->m_loop.get();
}

void LoopPool::StopPool() const
{
    for (auto & data : m_loop_pool)
    {
        data->m_status = false;
        data->m_schedule_event->Cancel();
    }
}

void LoopPool::Schedule(const std::shared_ptr<LoopData>& loop_data)
{
    if (loop_data->m_status)
    {
        loop_data->m_schedule_event->ExpireFromNow(10 * 1000, [loop_data, this]() {

            Schedule(loop_data);
        });
    }
}

void LoopPool::StartThread(const std::shared_ptr<LoopData>& loop_data)
{
    Schedule(loop_data);
    loop_data->m_loop->Run();
}



